/*
 * Copyright (c) 2011 CCX(China) Co.,Ltd. All Rights Reserved.
 *
 * This software is the confidential and proprietary information of
 * CCX(China) Co.,Ltd. ("Confidential Information").
 * It may not be copied or reproduced in any manner without the express 
 * written permission of CCX(China) Co.,Ltd.
 * 
 *	Created on 2011-1-5 下午01:37:01
 */
package cn.com.ccxe.input;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.com.ccxe.core.entity.Keyword;
import cn.com.ccxe.core.entity.CrawlExpression;
import cn.com.ccxe.core.entity.MonitorType;
import cn.com.ccxe.core.entity.Website;

/**
 *
 * XML数据读取器
 * @author hetao
 */
public class XmlRead implements Reader {

	private Document xmlConfig;
	private final Logger logger = LoggerFactory.getLogger(XmlRead.class);
	private final SAXReader saxReader = new SAXReader();
	private Element data;
	private Node websites;
	private Node keywords;
	private Node types;
	
	
	public XmlRead() throws DocumentException {
		try {
			xmlConfig = saxReader.read(XmlRead.class.getClassLoader().getResource("data.xml"));
			data = xmlConfig.getRootElement();
			websites = data.selectSingleNode("websites");
			keywords = data.selectSingleNode("keywords");
			types = data.selectSingleNode("types");
		} catch (DocumentException e) {
			xmlConfig = null;
			logger.error("WARNING: Could not find zebra.xml file in class path. I will use the default values.\n{}",e.getStackTrace());
			throw e;
		}
	}
	
	@SuppressWarnings("unchecked")
	public List<Website> readWebsite() {
		List<Website> result = new ArrayList<Website>();
		List<Element> list = websites.selectNodes("website");
		for (Iterator<Element> iter = list.iterator(); iter.hasNext();) {
			Element e = iter.next();
			result.add(recursionWebsite(e, null));
		}
		return result;
	}
	
	@SuppressWarnings("unchecked")
	public List<MonitorType> readMonitorType() {
		List<MonitorType> result = new ArrayList<MonitorType>();
		List list = types.selectNodes("type");
		for (Iterator iter = list.iterator(); iter.hasNext();) {
			Element e = (Element) iter.next();
			String type = e.attributeValue("type");
			if(!isEmpty(type)) {
				MonitorType monitorType = new MonitorType();
				monitorType.setType(type);
				result.add(monitorType);
			}
		}
		return result;
	}
	
	@SuppressWarnings("unchecked")
	public List<Keyword> readKeyword() {
		List<Keyword> result = new ArrayList<Keyword>();
		List list = keywords.selectNodes("keyword");
		for (Iterator iter = list.iterator(); iter.hasNext();) {
			Element e = (Element) iter.next();
			String text = e.attributeValue("text");
			if(!isEmpty(text)) {
				Keyword keyword = new Keyword();
				keyword.setText(text);
				result.add(keyword);
			}
		}
		return result;
	}

	@SuppressWarnings("unchecked")
	private Website recursionWebsite(Element e , Website parent) {
		String name = e.attributeValue("name");
		String path = e.attributeValue("path");
		String isList_str = e.attributeValue("isList");
		String description = e.attributeValue("description");
		
		if(isEmpty(description)) {
			description = "";
		}
		if(isEmpty(path)) {
			path = "";
		}
		if(isEmpty(path)) {
			path = "";
		}
		if(isEmpty(isList_str)) {
			isList_str = "0";
		}
		
		Website website = new Website();
		website.setParent(parent);
		if(parent == null) {
			website.setParentId(0);
		}
		website.setName(name);
		website.setPath(path);
		short isList = Short.valueOf(isList_str);
		website.setIsList(isList);
		website.setDiscription(description);
		if(isList == 1) {
			CrawlExpression crawlRule = new CrawlExpression();
			crawlRule.setModuleId(website.getId());
			Node rule = (Node) e.selectSingleNode("rule");
			if(rule != null) {
				crawlRule.setListPageExpre(rule.selectSingleNode("list-rule").getText());
				crawlRule.setArticleListExpre(rule.selectSingleNode("article-rule").getText());
			}
			website.setListPage(crawlRule);
			return website;
		}
		List childen = e.selectNodes("website");
		List<Website> childenWebsite = new ArrayList<Website>();
		for (Iterator iter = childen.iterator(); iter.hasNext();) {
			Element child = (Element) iter.next();
			childenWebsite.add(recursionWebsite(child, website));
		}
		website.setChildren(childenWebsite);
		return website;
	}
	
    public static boolean isEmpty(String str) {
        return str == null || str.length() == 0;
    }
    
	public static void main(String[] args) throws DocumentException {
		XmlRead read = new XmlRead();
		List<Website> websites = read.readWebsite();
		List<Keyword> keywords = read.readKeyword();
		List<MonitorType> types = read.readMonitorType();
		for(int i = 0; i < websites.size(); i++) {
			Website website = websites.get(i);
			print(website,0);
		}
		for (MonitorType monitorType : types) {
			System.out.println("type: "+monitorType);
		}
		for (Keyword k : keywords) {
			System.out.println("keyword: "+k);
		}
	}
	
	private static void print(Website website,int count) {
		System.out.println(appent(count)+website);
		List<Website> list = website.getChildren();
		if(list!= null && list.size() > 0) {
		count = count+1;
			for (Website w : list) {
				print(w,count);
			}
		}
	}
	
	public static String appent(int i) {
		StringBuilder sb = new StringBuilder("|_");
		for (int j = 0; j < i; j++) {
			sb.append("____|");
		}
		return sb.toString();
	}
}
